﻿using BingFa.Entity;
using BingFa.UI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BingFa.UI.Controllers
{
    public class HomeController : Controller
    {
        //http://www.cnblogs.com/chenwolong/p/7506299.html
        // GET: /Home/

        public JsonResult Index()
        {
            //IndexModel M = new IndexModel();
            int C = LockForEF();
            //1.5  模拟耗时
            //Thread.Sleep(500); //消耗半秒钟
            int retry = 10;
            while (C < 0 && retry > 0)
            {
                retry--;
                C = LockForEF();
            }
            return Json(1,JsonRequestBehavior.AllowGet);
        }
        public int LockForEF()
        {
            int productId = 1;
            int C = 0;
            using (SaveChangesForBF context = new SaveChangesForBF())
            {
                var InventoryLogDbSet = context.InventoryLog;
                var InventoryDbSet = context.Inventory;//库存表

                using (var Transaction = context.Database.BeginTransaction())
                {
                    //减少库存操作
                    var Inventory_Mol = InventoryDbSet.Where(A => A.ProductId == productId).FirstOrDefault();//库存对象
                    Inventory_Mol.ProductCount = Inventory_Mol.ProductCount - 1;
                    C = context.SaveChanges();
                    //插入日志
                    InventoryLog LogModel = new InventoryLog()
                    {
                        Title = "插入一条数据，用于计算是否发生并发",

                    };
                    InventoryLogDbSet.Add(LogModel);
                    context.SaveChanges();
                    //1.5  模拟耗时
                    //Thread.Sleep(500); //消耗半秒钟
                    Transaction.Commit();
                }

            }
            return C;
        }

    }
}
